package com.triplelink.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

public final class GsonUtil {
	
	private static final Gson GSON = new Gson();
	private static final Gson GSON_PRETTY = new GsonBuilder().setPrettyPrinting().create();
	
	private GsonUtil() {
		
	}

	public static Gson getGson() {
		return GSON;
	}
	
	public static String getString(Object obj) {
		return GSON.toJson(obj).toString();
	}
	
	public static String getString(String json, Class<?> type) {
		return getString(GSON.fromJson(json, type));
	}
	
	public static String getPrettyString(Object obj) {
		return GSON_PRETTY.toJson(obj).toString();
	}
	
	public static String getPrettyString(String json, Class<?> type) {
		return getString(GSON_PRETTY.fromJson(json, type));
	}
	
	public static <T extends Object> T getObject(String json, Class<T> clazz) {
		
		if (StringUtil.isBlank(json)) {
			return null;
		}
		
		return GSON.fromJson(json, clazz);
	}
	
	public static JsonElement getJsonElement(Object obj) {
		return GSON.toJsonTree(obj);
	}
	
	public static JsonObject getJsonObject(String json) {
		
		JsonElement jsonElement =  GSON.fromJson(json, JsonElement.class);
		
		if (jsonElement == null) {
			return null;
		}
		
		return jsonElement.getAsJsonObject();
	}
	
	public static JsonElement getJsonElement(String primitivo) {
		return new JsonPrimitive(primitivo);
	}
	
	public static JsonElement getJsonElement(Number primitivo) {
		return new JsonPrimitive(primitivo);
	}

	public static void addArray(JsonObject json, String property, Object... objetos) {
		
		JsonArray jsonArray = new JsonArray();
		
		if (objetos != null) {
			for (Object objeto : objetos) {
				jsonArray.add(new JsonPrimitive(objeto.toString()));
			}
		}
		
		json.add(property, jsonArray);
	}
	
	public static JsonArray getJsonArray(String array) {
		return GSON.fromJson(array, JsonElement.class).getAsJsonArray();
	}
}
